package com.dn.lotte.ui.purchase.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.dn.lotte.R;
import com.dn.lotte.api.ServerApi;
import com.dn.lotte.bean.PursezhlistBean;
import com.dn.lotte.bean.RemoveBean;
import com.dn.lotte.bean.SelectNumberBean;
import com.dn.lotte.bean.ZHTBean;
import com.dn.lotte.ui.purchase.activity.BetSuccessActivity;
import com.dn.lotte.ui.purchase.adapter.PursueAdapter;
import com.dn.lotte.utils.CommonUtils;
import com.easy.common.base.BaseFragment;
import com.easy.common.commonwidget.RippleView;
import com.google.gson.Gson;
import com.lzy.okgo.model.HttpParams;
import com.qmuiteam.qmui.util.QMUIDisplayHelper;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import com.qmuiteam.qmui.widget.popup.QMUIListPopup;
import com.qmuiteam.qmui.widget.popup.QMUIPopup;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

/**
 * 111
 * Created by ASUS on 2017/10/26.
 */
@SuppressLint("ValidFragment")
public class PursueFragment extends BaseFragment implements RippleView.OnRippleCompleteListener {
    @Bind(R.id.rv_list)
    RecyclerView mRecyclerView;
    @Bind(R.id.okBtn)
    RippleView okBtn;
    @Bind(R.id.rlv_ok)
    RippleView rlvOk;
    private String tag;
    private String selectData;
    private List<PursezhlistBean.TableBean> mlist = new ArrayList<>();
    private QMUIListPopup mListPopup;
    private List<SelectNumberBean.NumberBean> lastlist;
    private PursueAdapter mAdapter;
    private RelativeLayout rlMultiple;
    private RelativeLayout rlYield;
    private RelativeLayout rlSeparate;
    private View view1;
    private View view2;
    private View view3;
    private RippleView srlPursenumber;
    private TextView tvAllPeriods;
    private TextView tvPursenumber;
    private List<PursezhlistBean.TableBean> mnewlist;
    private TextView tv_moeny;
    private String modemoney;
    private String num;
    private EditText cet_multiple;
    private String multiple;
    private EditText cet_separate;
    private String allq;
    private String lotteryId;
    private String balls;
    private String mode;
    private String playId;
    private String singelBouns;
    private String point;
    private String price;
    private String strPos;
    private ZHTBean zhtBean;
    private String isstop = "1";
    private String type = "0";
    private String isClear;

    public PursueFragment(String s, String selectData) {
        this.tag = s;
        this.selectData = selectData;
    }

    @Override
    protected int getLayoutResource() {
        return R.layout.fragment_purse;
    }

    @Override
    public void initPresenter() {

    }

    @Override
    protected void initView() {
        CommonUtils.setSelectNumberList(selectData);
        lastlist = CommonUtils.getSelectNumberList();
        getcount();
        loadView();
    }

    private void loadView() {
        View inflate = LayoutInflater.from(getActivity()).inflate(R.layout.head_pursuefragment, null);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mAdapter = new PursueAdapter(R.layout.item_pursue, mlist);
        mRecyclerView.setAdapter(mAdapter);
        mAdapter.addHeaderView(inflate);
        rlMultiple = (RelativeLayout) inflate.findViewById(R.id.rl_multiple);
        rlYield = (RelativeLayout) inflate.findViewById(R.id.rl_yield);
        rlSeparate = (RelativeLayout) inflate.findViewById(R.id.rl_separate);
        view1 = (View) inflate.findViewById(R.id.view1);
        view2 = (View) inflate.findViewById(R.id.view2);
        tvPursenumber = (TextView) inflate.findViewById(R.id.tv_pursenumber);
        tvAllPeriods = (TextView) inflate.findViewById(R.id.tv_all_periods);
        tv_moeny = (TextView) inflate.findViewById(R.id.tv_moeny);
        cet_multiple = (EditText) inflate.findViewById(R.id.cet_multiple);
        cet_separate = (EditText) inflate.findViewById(R.id.cet_separate);
        srlPursenumber = (RippleView) inflate.findViewById(R.id.srl_pursenumber);
        srlPursenumber.setOnRippleCompleteListener(this);
        okBtn.setOnRippleCompleteListener(this);
        rlvOk.setOnRippleCompleteListener(this);
        if (tag.equals("1")) {
            rlYield.setVisibility(View.VISIBLE);
            rlSeparate.setVisibility(View.GONE);
            view1.setVisibility(View.VISIBLE);
            view2.setVisibility(View.GONE);
        } else if (tag.equals("2")) {
            rlYield.setVisibility(View.GONE);
            rlSeparate.setVisibility(View.GONE);
            view1.setVisibility(View.GONE);
            view2.setVisibility(View.GONE);
        } else if (tag.equals("3")) {
            rlYield.setVisibility(View.GONE);
            rlSeparate.setVisibility(View.VISIBLE);
            view1.setVisibility(View.GONE);
            view2.setVisibility(View.VISIBLE);
        }
        loadAll();
    }

    private void loadAll() {
        //注数
        num = lastlist.get(0).getNum();
        //模式
        mode = lastlist.get(0).getModel();
        //号码
        balls = lastlist.get(0).getBalls();
        lotteryId = lastlist.get(0).getLotteryId();//彩种id
        //玩法id
        playId = lastlist.get(0).getPlayId();
        //奖金
        singelBouns = lastlist.get(0).getSingelBouns();
        point = lastlist.get(0).getPoint();//返点
        price = lastlist.get(0).getPrice();//单倍金额
        strPos = lastlist.get(0).getStrPos();//方式
        //方式
        isClear = lastlist.get(0).getIsClear();

        if (mode.equals("元")) {
            modemoney = "1";
        } else if (mode.equals("角")) {
            modemoney = "0.1";
        } else if (mode.equals("分")) {
            modemoney = "0.01";
        } else if (mode.equals("厘")) {
            modemoney = "0.001";
        }
        //期数
        allq = tvAllPeriods.getText().toString();
        //倍数
        multiple = cet_multiple.getText().toString();
        if (mnewlist != null) {
            if (tag.equals("3")) {
                loadfb();//翻倍
            } else {
                loadmargin();//利润率
            }
        }
    }

    //利润率，同倍
    private void loadmargin() {
        for (int i = 0; i < mnewlist.size(); i++) {
            mnewlist.get(i).setCount(multiple);
            mnewlist.get(i).setPrice(Integer.parseInt(multiple) * Double.parseDouble(modemoney) * Double.parseDouble(price)* Double.parseDouble(num) + "");
            Log.e("kkkkk", Integer.parseInt(multiple) * Double.parseDouble(modemoney) * Double.parseDouble(price) + "");
        }

        float allmoney = (float) (Integer.parseInt(num) * Double.parseDouble(modemoney) * Integer.parseInt(allq) * Integer.parseInt(multiple));
        tv_moeny.setText(allmoney + "");
        if (mnewlist != null) {
            mAdapter.setNewData(mnewlist);
            loadbeanAll(mnewlist, allmoney + "");
        }
    }

    private void loadbeanAll(List<PursezhlistBean.TableBean> mnewlist, String allmoney) {
        zhtBean = new ZHTBean();
        List<ZHTBean.TableBean> mlist = new ArrayList<>();
        for (int i = 0; i < mnewlist.size(); i++) {
            ZHTBean.TableBean zhtable = new ZHTBean.TableBean();
            zhtable.setLotteryId(lotteryId);//彩种id
            zhtable.setIssueNum(mnewlist.get(i).getSn());//期号
            zhtable.setPlayId(playId);//玩法id
            zhtable.setPrice(price);//单倍金额
            zhtable.setTimes(mnewlist.get(i).getCount());//倍数
            Log.e("kkkkk1", mnewlist.get(i).getPrice() + "");
            zhtable.setNum(num);//注数
            zhtable.setSingelBouns(singelBouns);//奖金
            zhtable.setPoint(point);//返点
            zhtable.setBalls(balls);//号码
            zhtable.setStrPos(strPos);
            zhtable.setIsClear(isClear);
            zhtable.setAlltotal(mnewlist.get(i).getPrice());//总金额
            mlist.add(zhtable);
        }
        zhtBean.setLotteryId(lotteryId);
        zhtBean.setStartIssueNum(mnewlist.get(0).getSn());//开始期号
        zhtBean.setTotalNums(mnewlist.size() + "");
        zhtBean.setIsStop(isstop);
        zhtBean.setTotalSums(allmoney + "");
        zhtBean.setTable(mlist);
    }

    //翻倍
    private void loadfb() {
        for (int i = 0; i < mnewlist.size(); i++) {
            mnewlist.get(i).setCount((int) Math.pow(Double.parseDouble(multiple),
                    i / Integer.valueOf(cet_separate.getText().toString())) + "");
            double pow = Math.pow(Double.parseDouble(multiple),
                    i / Integer.valueOf(cet_separate.getText().toString()));
            mnewlist.get(i).setPrice(pow * Double.parseDouble(num) * Double.parseDouble(modemoney) + "");

        }
        float allmoneyf = 0;
        for (int i = 0; i < mnewlist.size(); i++) {
            allmoneyf += Double.parseDouble(mnewlist.get(i).getPrice());
        }
        tv_moeny.setText(allmoneyf + "");
        if (mnewlist != null) {
            mAdapter.setNewData(mnewlist);

            loadbeanAll(mnewlist, allmoneyf + "");
        }
    }

    @Override
    public void onComplete(RippleView rippleView) {
        switch (rippleView.getId()) {
            case R.id.srl_pursenumber:
                initListPopupIfNeed();
                mListPopup.setAnimStyle(QMUIPopup.ANIM_GROW_FROM_LEFT);
                mListPopup.setPreferredDirection(QMUIPopup.DIRECTION_BOTTOM);
                mListPopup.show(rippleView);
                break;
            case R.id.rlv_ok:
                if (!tvPursenumber.getText().toString().equals("")) {
                    type = "0";
                    showDialogstop();
                } else {
                    showShortToast("请先选择期数");
                }
                break;
            case R.id.okBtn:
                if (mnewlist != null) {
                    if (type.equals("1")) {
                        showShortToast("请先生成追号单");
                    } else {
                        showDialog();
                    }
                } else {
                    showShortToast("请先生成追号单");
                }
                break;
        }
    }

    private void showDialog() {
        new QMUIDialog.MessageDialogBuilder(getActivity())
                .setTitle("追号单已生成，")
                .setMessage("是否确定投注?")
                .addAction("取消", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        dialog.dismiss();
                    }
                })
                .addAction("确定", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        loadzh();
                        dialog.dismiss();
                    }
                })
                .show();

    }

    private void loadzh() {
        Gson gson = new Gson();
        String json = gson.toJson(zhtBean);
        ServerApi.setzhuihao(json)
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                        startProgressDialog();
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<RemoveBean>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        stopProgressDialog();
                    }

                    @Override
                    public void onNext(@NonNull RemoveBean removeBean) {
                        stopProgressDialog();
                        if (removeBean.getResult().equals("1")) {
                            type = "1";
                            Intent intent=new Intent(getActivity(),BetSuccessActivity.class);
                            intent.putExtra("strmoney",tv_moeny.getText().toString());
                            intent.putExtra("tag","1");
                            startActivity(intent);
                            tv_moeny.setText("");
                            List<PursezhlistBean.TableBean> mnewlist = new ArrayList<>();
                            mAdapter.setNewData(mnewlist);
                        }
                        showShortToast(removeBean.getReturnval());

                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        stopProgressDialog();

                    }

                    @Override
                    public void onComplete() {
                        stopProgressDialog();

                    }
                });
    }

    //获取数据
    public void getcount() {
        HttpParams params = new HttpParams();
        params.put("lid", lastlist.get(0).getLotteryId());
        ServerApi.getpursecount(params)
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                        startProgressDialog();
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<PursezhlistBean>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        stopProgressDialog();
                    }

                    @Override
                    public void onNext(@NonNull PursezhlistBean pursezhlistBean) {
                        stopProgressDialog();
                        if (pursezhlistBean.getResult().equals("1")) {
                            mlist = pursezhlistBean.getTable();
                            //
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        stopProgressDialog();
                    }

                    @Override
                    public void onComplete() {
                        stopProgressDialog();
                    }
                });
    }

    private void initListPopupIfNeed() {
        if (mListPopup == null) {
            final List<String> mlists = new ArrayList<>();
            for (PursezhlistBean.TableBean bean : mlist) {
                mlists.add(bean.getNo() + " 期");
            }
            ArrayAdapter adapter = new ArrayAdapter<>(getActivity(), R.layout.simple_list_item, mlists);
            mListPopup = new QMUIListPopup(getActivity(), QMUIPopup.DIRECTION_NONE, adapter);
            mListPopup.create(QMUIDisplayHelper.dp2px(getActivity(), 120), QMUIDisplayHelper.dp2px(getActivity(), 220), new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                    tvPursenumber.setText(mlists.get(i));
                    tvAllPeriods.setText(mlist.get(i).getNo());
                    loadzd(mlist.get(i).getNo());
                    mListPopup.dismiss();
                }
            });
            mListPopup.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                }
            });
        }
    }


    private void loadzd(String number) {
        mnewlist = new ArrayList<>();

        for (int i = 0; i < Integer.parseInt(number); i++) {
            mnewlist.add(mlist.get(i));
        }

    }

    private void showDialogstop() {
        new QMUIDialog.MessageDialogBuilder(getActivity())
                .setTitle("追号单已生成")
                .setMessage("是否中奖后停止追号?")
                .addAction("否", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        isstop = "0";
                        loadAll();
                        dialog.dismiss();

                    }
                })
                .addAction("是", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        isstop = "1";
                        loadAll();
                        dialog.dismiss();
                    }
                })
                .show();

    }
}
